﻿using Grpc.Core;
using Grpc.Core.Interceptors;
using Md.Demo.Entity.MongoModels;
using Md.Demo.Tools;
using Microsoft.Extensions.Logging;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Md.Demo.Service
{
    public class ServerInterceptor : Interceptor
    {
        private static readonly Logger _logger = LogManager.GetLogger("logger");


        private readonly IElasticSearchServer _elasticSearchServer;
        public ServerInterceptor(IElasticSearchServer elasticSearchServer)
        {
            this._elasticSearchServer = elasticSearchServer;
        }
        public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod<TRequest, TResponse> continuation)
        {
            try
            {
                return await base.UnaryServerHandler(request, context, continuation);
            }
            catch (RpcException ex)
            {
                _logger.Error($"rpc server error: {ex.Message}");
                await _elasticSearchServer.CreateAsync(new ExceptionLogger { message = ex.Message, detail = ex });
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.Error($"code server error: {ex.Message}");
                await _elasticSearchServer.CreateAsync(new ExceptionLogger { message = ex.Message, detail = ex });
                throw new RpcException(new Status(StatusCode.Internal, ex.Message, ex));
            }
        }
    }
}
